import type { RoleRoutes } from "@/types/menu";
import { createSlice, type PayloadAction } from "@reduxjs/toolkit";
import { addRoute } from "@/router/index";
import React, { lazy } from "react";
import { Navigate, type RouteObject } from "react-router-dom";
import type { MenuProps } from "antd";

type MenuItem = Required<MenuProps>["items"][number];
interface MenuState {
  /** 后端返回的动态路由 */
  dynamicMenu: RoleRoutes[];
  /** 菜单 */
  menus: MenuItem[];
  /** 菜单折叠状态 */
  collapsed: boolean;
}

const initialState: MenuState = {
  dynamicMenu: [],
  menus: [],
  collapsed: false,
};

const modules = import.meta.glob("@/pages/**/*.tsx");

// 将后端路由转换为前端路由配置
function convertToRouteObject(roleRoute: RoleRoutes): RouteObject {
  const { path, name, component, redirect, meta, children } = roleRoute;

  // 动态导入组件
  let routeElement: React.ReactNode | undefined;

  if (component) {
    // 根据组件路径动态导入

    const componentPath = `/src/pages/${component}.tsx`;
    const componentModule = modules[componentPath];
    if (componentModule) {
      const LazyComponent = lazy(componentModule as () => Promise<{ default: React.ComponentType }>);
      routeElement = React.createElement(LazyComponent);
    }
  }

  const route: RouteObject = {
    path,
    element: routeElement,
    handle: {
      meta: {
        title: meta?.title || name,
        icon: meta?.icon,
        externalLinks: meta?.externalLinks,
        type: meta?.type,
        redirect,
      },
    },
  };

  if (children && children.length > 0) {
    route.children = [];
    if (redirect) {
      // 加上重定向路由
      route.children.push({
        element: React.createElement(Navigate, { to: redirect || "/" }),
        index: true,
      });
    }
    route.children.push(...children.map((child) => convertToRouteObject(child)));
  }

  return route;
}

function handleMenuByRoutes(routes: RoleRoutes[]): any {
  return routes
    .filter((item) => item.meta.type === "menu")
    .map((route) => {
      const { path, name, meta, children } = route;

      const menuItem: MenuItem = {
        key: path,
        label: meta?.title || name,
        icon: meta?.icon,
        children: children && children.length > 0 ? handleMenuByRoutes(children) : undefined,
      };

      return menuItem;
    });
}

export const menuSlice = createSlice({
  name: "menu",
  initialState,
  reducers: {
    setDynamicMenu(state, action: PayloadAction<RoleRoutes[]>) {
      state.dynamicMenu = action.payload;

      // 将后端路由转换为前端路由并添加到路由配置中
      action.payload.forEach((route) => {
        const frontendRoute = convertToRouteObject(route);
        addRoute(frontendRoute);
      });

      // 菜单
      state.menus = handleMenuByRoutes(action.payload);
    },
    setCollapsed(state, action: PayloadAction<boolean>) {
      state.collapsed = action.payload;
    },
  },
});

// 导出同步 action creators
export const { setDynamicMenu, setCollapsed } = menuSlice.actions;

export default menuSlice.reducer;
